package com.zwf.domain.strategy.service.rule.impl;

import com.zwf.domain.strategy.model.entity.RuleActionEntity;
import com.zwf.domain.strategy.model.entity.RuleMatterEntity;
import com.zwf.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.zwf.domain.strategy.repository.IStrategyRepository;
import com.zwf.domain.strategy.service.annotation.LogicStrategy;
import com.zwf.domain.strategy.service.rule.ILogicFilter;
import com.zwf.domain.strategy.service.rule.factory.DefaultLogicFactory;
import com.zwf.types.common.Constants;
import com.zwf.types.enums.ResponseCode;
import com.zwf.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author zwf
 * @description 【抽奖前规则】根据抽奖权重返回可抽奖范围KEY
 * @date 2024/7/5 21:12
 */
@Slf4j
@Component
@LogicStrategy(logicModel = DefaultLogicFactory.LogicModel.RULE_WIGHT)
public class RuleWeightLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Autowired
    private IStrategyRepository repository;

    /**
     * 权重规则过滤；
     * 1. 权重规则格式；0:101,102,103,104 2000:101,102,103,104,105 4000:101,102,103,104,105,106 6000:102,103,104,105,106,107,108,109
     * 2. 解析数据格式；判断哪个范围符合用户的特定抽奖范围
     *
     * @param ruleMatterEntity 规则物料实体对象
     * @return 规则过滤结果
     */

    @Override
    public RuleActionEntity filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-权重范围 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());

        //1、查询用户积分消耗积累
        Integer accumulate = repository.queryPointAccumulate( ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId());

        //2、查询规则值并解析
        String ruleValue = repository.queryStrategyRuleValue(ruleMatterEntity.getStrategyId(), ruleMatterEntity.getAwardId(), ruleMatterEntity.getRuleModel());
        if(ruleValue == null){
            throw new AppException(ResponseCode.STRATEGY_RULE_VALUE_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_VALUE_IS_NULL.getInfo());
        }
        List<Integer> analyticalValue = getAnalyticalValue(ruleValue);
        if (null == analyticalValue || analyticalValue.isEmpty()) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                    .build();
        }

        //3、找出匹配的权值范围
        Collections.sort(analyticalValue);
        Integer nextValue = analyticalValue.stream()
                .filter(key -> accumulate>=key)
                .max(Integer::compareTo)
                .orElse(null);

        if (null != nextValue) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                            .strategyId(ruleMatterEntity.getStrategyId())
                            .ruleWeightValueKey(String.valueOf(nextValue))
                            .build())
                    .ruleModel(DefaultLogicFactory.LogicModel.RULE_WIGHT.getCode())
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                    .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                    .build();
        }

        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();

    }

    //解析权重规则值
    private List<Integer> getAnalyticalValue(String ruleValue){
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        List<Integer> ruleValueList = new ArrayList<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueList;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueList.add(Integer.valueOf(parts[0]));
        }
        return ruleValueList;

    }

}
